<template>
    <div claaa="eduAdmin">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>客户管理</el-breadcrumb-item>
                <el-breadcrumb-item>售前管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-card class="filter-container or-add-btn" shadow="never">
                <div style="padding-bottom: 10px">
                    <i class="el-icon-search"></i>&nbsp;
                    <span>{{ momaclassify.title }}筛选搜索</span>
                    <el-button style="float: right" type="primary" @click="handleSearchList()" size="small">查询搜索</el-button>
                    <el-button style="float: right; margin-right: 15px" @click="handleResetSearch()"
                        size="small">重置</el-button>
                </div>
                <div style="width: 100%; display: flex">
                    <div style="margin-top: 15px; width: 50%">
                        <el-form :inline="true" :model="listQuery" size="small" label-width="100px">
                            <el-row :gutter="24">
                                <el-col :span="8">
                                    <el-form-item label="平台名称：">
                                        <el-autocomplete v-if="/(SYS_ADMIN|ADMIN)/.test(roles[0])" class="inline-input"
                                            v-model="oidValue" value-key="title" :fetch-suggestions="querySearch"
                                            placeholder="请输入内容" @select="handleSelect" style="width: 80%"></el-autocomplete>
                                        <el-select v-else v-model="listQuery.oid" class="input-width" filterable
                                            placeholder="请选择平台" @clear="clearSelect" @change="changeOid"
                                            :clearable="roles[0] == 'SYS_ADMIN'">
                                            <!-- <el-option v-for="item in orgArrs" :key="item.id" :value="item.id" :label="item.name"></el-option> -->
                                            <el-option v-for="item in orgArr" :key="item.id" :value="item.id"
                                                :label="item.name"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="学生名称：">
                                        <el-input style="width: 80%" v-model="listQuery.studentName" class="input-width"
                                            placeholder="学生姓名" clearable></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="家长姓名：">
                                        <el-input style="width: 80%" v-model="listQuery.parentName" class="input-width"
                                            placeholder="家长姓名" clearable></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="24">
                                <el-col :span="8">
                                    <el-form-item label="家长电话：">
                                        <el-input style="width: 80%" v-model="listQuery.phone" class="input-width"
                                            placeholder="家长电话" clearable></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="自定义：">
                                        <el-select v-model="listQuery.customTag" style="width: 80%">
                                            <el-option value="0" label="否"></el-option>
                                            <el-option value="1" label="是"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                    <div style="margin: -30px 100px; width: 15%">
                        <inviteCode v-if="urlText" :urlText="urlText"></inviteCode>
                    </div>
                </div>
            </el-card>
            <el-button icon="el-icon-circle-plus-outline" type="primary" class="or-add-btn" @click="addOr">添加</el-button>
            <el-button icon="el-icon-document" type="primary" class="or-add-btn" @click="uploadOr">导出</el-button>
            <el-button type="primary" class="or-add-btn" @click="showhideRowExpand('', true)">一键展开</el-button>

            <el-table ref="mytable" class='mytable' :row-class-name="expandShowClass" :data="tableData" border>
                <el-table-column type="expand" label="">
                    <template slot-scope="props">
                        <custom-track @updateFun="updateFun"
                            :tableData="JSON.parse(JSON.stringify(props.row['children']))" />
                    </template>
                </el-table-column>
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="title" label="平台名称"></el-table-column>
                <el-table-column prop="studentName" label="学生名称"></el-table-column>
                <el-table-column prop="gradeName" label="学生年级"></el-table-column>
                <el-table-column prop="parentName" label="家长名称"></el-table-column>
                <el-table-column prop="phone" label="家长电话"></el-table-column>
                <el-table-column prop="subjectName" label="学科名称"></el-table-column>
                <el-table-column prop="editionName" label="版本名称"></el-table-column>
                <el-table-column prop="learningGradeName" label="年级名称"></el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>

                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button v-if="scope.row.customTag == 1" type="text" icon="el-icon-delete"
                            @click="deleteAccount(scope.row)">删除</el-button>
                        <el-button type="text" icon="el-icon-edit" @click="addTrack(scope.row)">新增跟踪</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="listQuery.pageNum"
                    :page-size="listQuery.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>

        </div>

        <!-- 新建/编辑 客户弹出框 -->
        <el-dialog :title="tit" :close-on-click-modal="false" :visible.sync="editVisible" width="400px">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row :gutter="24" v-if="tit == '编辑客户'">
                    <el-col :span="22">
                        <!-- 编辑时 -->
                        <el-form-item label="平台选择" prop="oid">
                            <el-select :disabled="tit == '编辑客户'" v-model="form.oid" style="width: 228px"
                                @change="clearCampusId($event)">
                                <!-- <el-option v-for="item in orgArr" :key="item.id" :label="item.name" :value="item.id"></el-option> -->
                                <el-option :label="form.title" :value="form.oid"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" v-else>
                    <el-col :span="22">
                        <el-form-item label="平台选择" prop="oid">
                            <el-select v-model="form.oid" style="width: 228px" @change="clearCampusId($event)">
                                <el-option v-for="item in orgArr" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="家长名称" prop="parentName">
                            <el-input v-model="form.parentName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="家长电话" prop="phone">
                            <el-input v-model="form.phone"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="学生姓名" prop="studentName">
                            <el-input v-model="form.studentName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="学生性别" prop="gender">
                            <el-select v-model="form.gender" style="width: 228px">
                                <el-option :value="1" label="男"></el-option>
                                <el-option :value="0" label="女"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="学生年级" prop="gradeId">
                            <el-select v-model="form.gradeId" style="width: 228px">
                                <el-option v-for="item in grade" :value="Number(item.id)" :key="item.id"
                                    :label="item.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" v-show="tit == '添加客户'">
                    <el-col :span="22">
                        <el-form-item label="学科" prop="subjectId">
                            <el-select v-model="form.subjectId" style="width: 228px">
                                <el-option v-for="item in allBookData" :value="item.id" :key="item.id"
                                    :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" v-show="tit == '添加客户'">
                    <el-col :span="22">
                        <el-form-item label="版本" prop="editionId">
                            <el-select v-model="form.editionId" style="width: 228px">
                                <el-option v-for="item in bookList['editions']" :value="item.id" :key="item.id"
                                    :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" v-show="tit == '添加客户'">
                    <el-col :span="22">
                        <el-form-item label="年级" prop="learningGradeId">
                            <el-select v-model="form.learningGradeId" style="width: 228px">
                                <el-option v-for="item in bookList['grades']" :value="item.id" :key="item.id"
                                    :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 修改客户类型 -->
                <el-row :gutter="24" v-show="tit == '编辑客户'">
                    <el-col :span="22">
                        <el-form-item label="客户类型" prop="customerType">
                            <el-select v-model="form.customerType" style="width: 228px">
                                <el-option :value="1" label="售前"></el-option>
                                <el-option :value="2" label="售后"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" v-show="tit == '添加客户'">
                    <el-col :span="22">
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="form.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDig">取 消</el-button>
                <el-button type="primary" @click="saveEdit" v-debounce>确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新建/编辑 追踪编辑的弹出框 -->
        <el-dialog :title="titTrack" :close-on-click-modal="false" :visible.sync="editVisibleTrack" width="450px">
            <el-form ref="trackform" :model="trackform" :rules="trackrules" label-width="120px">
                <el-row :gutter="24" v-if="titTrack == '编辑追踪'">
                    <el-col :span="22">
                        <el-form-item label="客户名称" prop="clientName">
                            <el-input disabled :value="trackform.clientName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="客户状态" prop="status">
                            <el-select v-model="trackform.status" style="width: 228px">
                                <el-option v-for="item in Object.keys(statuns)" :key="'s' + item" :label="statuns[item]"
                                    :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="客户成熟度" prop="maturity">
                            <el-select v-model="trackform.maturity" style="width: 228px">
                                <el-option v-for="item in Object.keys(maturityns)" :key="'m' + item"
                                    :label="maturityns[item]" :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="客户成交" prop="isDeal">
                            <el-select v-model="trackform.isDeal" style="width: 228px">
                                <el-option label="是" :value="1"></el-option>
                                <el-option label="否" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="文字描叙" prop="description">
                            <el-input type="textarea" v-model="trackform.description"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <hr style="border:1px dashed rgba(0,0,0,0.1); margin:10px 0 15px 0">
                </hr>
                <el-row :gutter="24">
                    <el-col :span="22">
                        <div style="width: 100%; display: flex; justify-content: center">
                            <el-upload class="uploadClass" ref="upload" :action="uploadURI" :on-preview="filePreview"
                                :on-change="fileChange" :on-remove="fileRemove" :file-list="fileList"
                                :http-request="uploadFileList" :auto-upload="false">
                                <el-button slot="trigger" size="small" type="primary">获取文件</el-button>
                                <!-- <el-button style="margin-left: 10px" size="small" type="success"
                                    @click="fileSubmit">上传全部文件</el-button> -->
                                <div slot="tip" class="el-upload__tip">
                                    支持类型：txt,doc,docx,xls,xlsx,pdf,jpg,png,ico,bmp,jpeg
                                </div>
                                <div slot="tip" class="el-upload__tip">
                                    注意：txt文件的格式为utf-8, 另存为选文件格式即可
                                </div>
                                <div slot="tip" class="el-upload__tip">只能上传单个文件，且不超过20MB</div>
                            </el-upload>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisibleTrack = false">取 消</el-button>
                <el-button type="primary" @click="saveFileTrack" v-debounce>确 定</el-button>
            </span>
        </el-dialog>

        <!-- 是否导出追踪信息 -->
        <el-dialog title="导出配置" :close-on-click-modal="false" :visible.sync="uploadConfigFlag" width="400px">
            <div>
                <el-radio v-model="uploadConfig" label="1" border>带有追踪数据</el-radio>
                <el-radio v-model="uploadConfig" label="0" border>不带追踪数据</el-radio>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="uploadConfigFlag = false">取 消</el-button>
                <el-button :loading="uploadDataFlag" type="primary" @click="uploadEdit" v-debounce>确 定</el-button>
            </span>
        </el-dialog>

        <!-- 文件预览框 -->
        <el-dialog title="文件预览表格" :close-on-click-modal="false" :visible.sync="editVisiblePreview" width="400px">
            <el-table :data="fileListPreview" border>
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="name" label="文件名">
                    <template slot-scope="scope">
                        <p v-if="scope.row.name">
                            {{ scope.row.name.split('/').slice(-1)[0] }}
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="filePreview(scope.row.name, 1)">预览</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 预览的显示 图片/txt/pdf - 线下预览  -->
        <el-dialog custom-class="previewDiv" :title="previewName" width="80vw" :close-on-click-modal="false"
            :visible.sync="editVisiblePreviewOne">
            <iframe class="previewDivIframe" :src="previewURI"> </iframe>
        </el-dialog>
        <!-- 预览的显示 pdf - 线上预览  -->
        <el-dialog custom-class="previewDiv" :title="previewName" width="80vw" :close-on-click-modal="false"
            :visible.sync="editVisiblePreview_pdf">
            <vue-office-pdf :src="previewURI" />
        </el-dialog>
        <!-- 预览的显示 图片 - 线上预览  -->
        <el-dialog custom-class="previewDiv" :title="previewName" width="80vw" :close-on-click-modal="false"
            :visible.sync="editVisiblePreview_img">
            <img :src="previewURI" alt="">
        </el-dialog>
        <!-- 预览的显示 txt - 线上预览  -->
        <el-dialog custom-class="previewDiv" :title="previewName" width="80vw" :close-on-click-modal="false"
            :visible.sync="editVisiblePreview_txt">
            <div class="previewDivIframe" :text="previewTEXT"></div>
        </el-dialog>
        <!-- 预览的显示 doc/docx -->
        <el-dialog custom-class="previewDiv" :title="previewName" width="80vw" :close-on-click-modal="false"
            :visible.sync="editVisiblePreviewTwo">
            <vue-office-docx :src="previewURI" />
        </el-dialog>
        <!-- 预览的显示 xls/xlsx -->
        <el-dialog custom-class="previewDiv" :title="previewName" width="80vw" :close-on-click-modal="false"
            :visible.sync="editVisiblePreviewThree">
            <vue-office-excel :src="previewURI" />
        </el-dialog>

        <!-- 一键折叠 -->
        <div @click="showhideRowExpand('', false)" class="hideExpandDiv">
            折叠
        </div>

    </div>
</template>

<script>
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'
import '@vue-office/excel/lib/index.css'

import {
    getClientList,
    deleteClient,
    getAllBookList,
    addClient,
    getRelationBookList,
    updateClientInfo,
    getMechanismCampusList
} from '@/http/api/index';
import {
    addOrUpdateTrack,
    selectTrackList,
    clientAndTrackExport,
    deleteTrack,
    upploadFileText
} from '@/api/customtrack.js';
import { mapGetters } from 'vuex';
import store from '@/store'
import axios from 'axios'
import { getOrgList, getGradeSubjectTime } from '@/api/students';
import { formatDate } from '@/utils/date.js';
import img from '@/assets/img/logo_link/img.png';
import inviteCode from '@/components/page/component/inviteCode.vue';
import customTrack from '../components/customTrack.vue';
import { writeFun_array, writeFun_array_tree } from '@/assets/js/xlsx'
const defaultListQuery = {
    customerType: 1,
    pageNum: 1,
    pageSize: 10
};
const checkPhone = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('手机号不能为空'));
    } else {
        const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        if (reg.test(value)) {
            callback();
        } else {
            return callback(new Error('请输入正确的手机号'));
        }
    }
};
let url = window.location.href.split("/");
const urls = url[0] + url[1] + "//" + url[2] + "/";
url = null;
export default {
    name: 'teacher',
    data() {
        return {
            uploadURI: urls + 'client/uploadAttachment',  // 上传url
            reviewURI: this.$staticUrl, // 预览/下载url => https://xiaogoss.oss-cn-beijing.aliyuncs.com/



            remoteFlag: false,  // 线下/线上
            previewTEXT: "",

            uploadDataFlag: false,
            uploadConfigFlag: false,  // 导出配置框显示隐藏
            uploadConfig: '0', // 导出配置项  0:不带追踪 1带追踪
            subjectOK: [],  // 开设的学科id
            previewURI: '',  // 预览的链接
            editVisibleTrack: false,
            editVisiblePreview: false,
            editVisiblePreviewOne: false,  // 预览的文件查看
            editVisiblePreview_txt: false,
            editVisiblePreview_img: false,
            editVisiblePreview_pdf: false,
            editVisiblePreviewTwo: false, // doc/docx 预览
            editVisiblePreviewThree: false,  // xls/xlsx 预览
            previewName: '', // 要预览的文件名称
            fileList: [], // 已上传和待上传的文件
            fileListPreview: [], // 预览文件的表格
            img,
            urlText: '',
            momaclassify: {
                title: '',
                channel: ''
            },
            oidValue: '',
            listQuery: Object.assign(defaultListQuery),
            tit: '',
            titTrack: '',
            MoneyVisible: false,
            moneyform: {},
            tableData: [],
            allBookData: [],
            relationBookList: [],
            bookList: {
                // 学科选完后的 版本和年级
                editions: [],
                grades: []
            },
            statuns: {
                // 客户状态
                1: '成交客户',
                2: '潜在客户',
                3: '意向客户',
                4: '失败客户'
            },
            maturityns: {
                1: 'A+明确成交意向',
                2: 'A-有初步成交意向',
                3: 'B+初步联系有意向',
                4: 'B-初步联系意向是否成交',
                5: 'C+明显拒绝',
                6: 'C-无效客户'
            },
            grade: [
                { id: '110', label: '一年级' },
                { id: '120', label: '二年级' },
                { id: '130', label: '三年级' },
                { id: '140', label: '四年级' },
                { id: '150', label: '五年级' },
                { id: '160', label: '六年级' },
                { id: '170', label: '七年级' },
                { id: '180', label: '八年级' },
                { id: '190', label: '九年级' },
                { id: '210', label: '高一' },
                { id: '220', label: '高二' },
                { id: '230', label: '高三' }
            ],
            treeData: [],
            editVisible: false,
            editVisible2: false,
            pageTotal: 0,
            orgArr: [],
            orgArrs: [],

            abbreviation: '', // 机构名称
            form: {},
            trackform: {}, // 追踪的数据
            rules: {
                oid: [{ required: true, message: '请选择平台', trigger: 'change' }],
                studentName: [{ required: true, message: '请填写学生姓名', trigger: 'blur' }],
                parentName: [{ required: true, message: '请填写家长姓名', trigger: 'blur' }],
                // gender: [{ required: true, message: '请选择学生性别', trigger: 'blur' }],
                subjectId: [{ required: true, message: '请选择学科', trigger: 'change' }],
                editionId: [{ required: true, message: '请选择版本', trigger: 'change' }],
                gradeId: [{ required: true, message: '请选择学生年级', trigger: 'change' }],
                learningGradeId: [{ required: true, message: '请选择年级', trigger: 'change' }],
                phone: [
                    { required: true, message: '请填写联系方式', trigger: 'blur' },
                    { validator: checkPhone, trigger: ['blur'] }
                ]
            },
            trackrules: {
                status: [{ required: true, message: '请选择客户状态', trigger: 'change' }],
                maturity: [{ required: true, message: '请填写客户成熟度', trigger: 'change' }],
                isDeal: [{ required: true, message: '请填写客户成交', trigger: 'change' }]
            },
            curAddMax: '',
            curSubMax: ''
        };
    },
    components: {
        inviteCode,
        customTrack,
        VueOfficeExcel,
        VueOfficePdf,
        VueOfficeDocx
    },
    computed: {
        ...mapGetters(['userInfo', 'roles', 'orgInfo', 'campusList'])
    },
    created() {
        // 获取全部的平台
        this.$nextTick(() => {
            this.getMechanismCampusList({ channel: '' });
        });
    },
    mounted() {
        this.abbreviation = this.userInfo.abbreviation;
        let oid = this.userInfo.oriId || 0,
            id = this.userInfo.id || 0;
        let urls = window.location.href.split("/");
        urls = urls[0] + "//" + urls[2];
        this.urlText = `${urls}/admin/h5?oid=${oid}&id=${id}&type=5`;

        this.orgArr = this.orgInfo;
        if (!/(SYS_ADMIN|ADMIN)/.test(this.roles[0])) {
            this.listQuery.oid = this.userInfo.oriId;
        }
        this.listQuery = Object.assign({}, this.listQuery, defaultListQuery);
        // 获取售前的客户
        this.getClientList(this.listQuery);
        this.getAllBookList({ oid: this.userInfo.oriId });
        this.getRelationBookList({ oid: this.userInfo.oriId });

    },
    watch: {
        'form.subjectId'(nv, ov) {
            // 学科的修改 - 修改版本
            for (let item of this.allBookData) {
                if (item.id == nv) {
                    let arrs = [];
                    for (let item1 of item.children) {
                        if (this.relationBookList.includes(Number(item1['id']))) {
                            arrs.push(item1);
                        }
                    }
                    this.bookList['editions'] = arrs;
                    this.$set(this.bookList);
                    return;
                }
            }
            return;
        },
        'form.editionId'(nv, ov) {
            // 版本的修改 - 修改年级
            for (let item of this.allBookData) {
                if (item.id == this.form.subjectId) {
                    for (let item1 of item.children) {
                        if (item1.id == nv) {
                            this.bookList['grades'] = item1.children;
                            this.$set(this.bookList, 'grades', item1.children);
                            return;
                        }
                    }
                }
            }
            return;
        }
    },
    methods: {
        // 文件 -- 待上传的 {name: '', status:"ready"}, 成功的{name:'', urlReview:'预览网址', urlUpload:'下载网址'}
        // 文件上传至服务器
        uploadFileList(s) {
            let formdata = new FormData();
            formdata.append('file', s.file);
            axios.post(s.action, formdata, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'authorization': store.getters.token
                },
            }).then(response => {
                let data = response.data, filename = '';
                if (data.code == 200) {
                    this.$message.success("文件上传成功");
                    filename = data.data;
                } else {
                    this.$message.success("文件上传失败,前往编辑中添加");
                }
                this.fileList = [];
                // 触发上传成功监听
                filename = filename.replace(/\\/g, '/');
                this.$emit("upload", filename);
            }).catch(error => {
                console.log(error, "error");
            });
        },

        // --- 文件的获取 - 可检测文件大小和文件类型
        fileChange(file, fileList) {
            // console.log(file, "===========");
            if (file.size > 20 * 1024 * 1024) {
                this.$message.error("文件过大");
                this.$set(this.fileList);
                return;
            } else if (!(/\.(doc|docx|xls|xlsx|pdf|txt|jpg|png|ico|bmp|jpeg)$/.test(file.name))) {
                this.$message.error("只支持 txt,doc,docx,xls,xlsx,pdf,jpg,png,ico,bmp,jpeg");
                this.$set(this.fileList);
                return;
            }
            // 判断与线上的文件名是否相同 - 相同则提示用户文件名重复
            // 提交唯一文件
            let arrs = [];
            this.fileList.forEach((v, i) => {
                if (v.status != "ready") {
                    arrs.push(v);
                }
            })
            arrs.push(fileList[fileList.length - 1]);
            this.fileList = arrs;
        },
        // --- 文件的删除
        fileRemove(file, fileList) {
            this.fileList.forEach((item, i) => {
                if (file.name == item.name) {
                    this.fileList.splice(i, 1);
                    return false;
                }
            })
        },
        // --- 点击文件 - 预览文件 - 预览文件 
        filePreview(file, type) {
            // 判断是否是 xlsx还是xls 还是 doc,docx
            if (!type) { // 线上/线下
                if (file.urlReview) {  // 线上
                    this.previewURI = file.urlReview;
                    this.remoteFlag = true;
                } else {  // 线下
                    this.remoteFlag = false;
                    let typefile = "";
                    if (file.name.includes('pdf')) {
                        typefile = 'application/pdf';
                    } else if (/(jpg|png|ico|bmp|jpeg)/.test(file.name)) {
                        typefile = 'image/jpeg';
                    }
                    let fileS = new Blob([file.raw], { type: typefile })
                    this.previewURI = window.URL.createObjectURL(fileS);
                    setTimeout(function () {
                        window.URL.revokeObjectURL(this.previewURI);   // 释放URL
                    }, 1000);
                }

            } else {  // 点击预览-线上的
                this.previewURI = this.reviewURI + file;
                this.remoteFlag = true;
            }

            if (/(doc|docx)/.test(file.name)) {
                this.previewName = "doc/docx的预览";
                this.editVisiblePreviewTwo = true;
            } else if (/(xls|xlsx)/.test(file.name)) {
                this.previewName = "xls/xlsx的预览";
                this.editVisiblePreviewThree = true;
            } else {
                if (this.remoteFlag) {  // 线上
                    if (file.name.includes('pdf')) {
                        this.previewName = "pdf预览";
                        this.editVisiblePreview_pdf = true;
                    } else if (/(jpg|png|ico|bmp|jpeg)/.test(file.name)) {
                        this.previewName = "图片预览";
                        this.editVisiblePreview_img = true;
                    } else if (file.name.includes('txt')) {
                        this.previewName = "文件预览";
                        axios.get(this.previewURI).then(text => {
                            if (text.status == 200) {
                                this.previewTEXT = text.data || "";
                            }
                        }).catch(err => { return; });
                        this.editVisiblePreview_txt = true;
                    }
                } else {  // 线下
                    this.previewName = "线下-文件预览";
                    this.editVisiblePreviewOne = true;
                }


            }
        },
        // 折叠和展开和特点展开和折叠
        // 参数1：clientId：需要操作的特定行，空则操作全部
        // 参数2：expandFlag：状态 true是展开 false折叠
        showhideRowExpand(clientId, expandFlag) {
            for (let v of this.tableData) {
                if ((v.id + "").includes(clientId)) {
                    this.$refs.mytable.toggleRowExpansion(v, expandFlag);
                }
            }
        },
        // 追踪的 修改/删除/预览/下载
        async updateFun(data) {
            // data = {clientId:1, id:1, type:2编辑 3删除 4预览 5下载}
            let type = data.type, clientid = data.clientId, id = data.id, attachmentUrl = data.attachmentUrl;
            if (type == 2) {
                let arr;
                for (let item of this.tableData) {
                    if (item.id == clientid) {
                        for (let item1 of item.children) {
                            if (item1.id == id) {
                                arr = item1;
                                break;
                            }
                        }
                        break;
                    }
                }
                if (arr) {
                    // 修改
                    this.updateTrack(arr);
                } else {
                    this.$message({
                        type: 'error',
                        message: '不能为空值!'
                    });
                }

            } else if (type == 3) {
                let i = 0, flag = false;
                for (let item of this.tableData) {
                    if (item.id == clientid) {
                        item.children.forEach((v, i) => {
                            if (v.id == id) {
                                item.children.splice(i, 1);
                                if (item.children.length == 0) {
                                    flag = true;
                                    item.showExpand = false;
                                }
                                return false;
                            }
                        });
                        break;
                    }
                    i++;
                }
                if (flag) {
                    this.tableData = JSON.parse(JSON.stringify(this.tableData));
                }

            } else if (type == 4) {
                // 预览
                // if(!(/(txt|pdf|jpg|png|ico|bmp|jpeg)/.test(attachmentUrl))){
                //     this.$message.error("不支持预览");
                //     return;
                // }
                let filename = attachmentUrl.split(",");
                let arr = [];
                for (let item of filename) {
                    arr.push({ name: item });
                }
                this.fileListPreview = arr;
                this.editVisiblePreview = true;

            } else if (type == 5) {
                // txt下载
                if (/(txt)/.test(attachmentUrl)) {
                    axios.get(this.reviewURI + attachmentUrl).then(text => {
                        if (text.status == 200) {
                            this.downloadTxt(attachmentUrl.split("/").slice(-1)[0], text.data, 1);
                        }
                    }).catch(err => { return; });
                }
                // // 图片下载
                // else if(/(jpg|png|ico|bmp|jpeg)/.test(attachmentUrl)){
                //     this.downloadTxt(attachmentUrl.split("/").slice(-1)[0], this.reviewURI + attachmentUrl, 2);
                // }
                else {
                    this.downloadTxt(attachmentUrl.split("/").slice(-1)[0], this.reviewURI + attachmentUrl, 2);
                }
                return;
            }
        },
        // a标签下载 txt 文件  图片类  type 1:txt 2:图片或者其他
        downloadTxt(fileName, content, type) {
            let a = document.createElement('a');
            if (type == 1) {
                a.href = 'data:text/plain;charset=utf-8,' + content
            } else {
                a.href = content;
            }
            a.download = fileName
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        },
        // 修改平台
        clearCampusId(e) {
            if (this.form.subjectId) {
                this.form.subjectId = '';
            }
            if (this.form.editionId) {
                this.form.editionId = '';
            }
            if (this.form.gradeId) {
                this.form.bookGrade = '';
            }
            this.bookList = { editions: [], grades: [] };
            this.getAllBookList({ oid: e });
            this.getRelationBookList({ oid: e });
            setTimeout(() => {
                this.getGradeSubjectTime(e);
            }, 500);
            return;
        },
        // 是否显示展开行图标
        expandShowClass(row) {
            // 没有子集 - 隐藏展开按钮
            if (!row.row.showExpand) {
                return 'row-expand-cover';
            }
        },
        getClientList(param) {
            getClientList(param).then(res => {
                if (res.code == 200) {
                    let arr = res.data.list;
                    this.pageTotal = res.data.total;
                    // 获取客户下面的追踪 - 拼接children
                    if (this.pageTotal > 0) {
                        let arrchild;
                        for (let item of arr) {
                            item['children'] = item.trackList;
                            delete item.trackList;
                            item['showExpand'] = false;
                            if (item['children'].length > 0) {
                                item['showExpand'] = true;
                                // 文件名的处理 \转/
                                for (let ii of item['children']) {
                                    if (ii.attachmentUrl) {
                                        ii.attachmentUrl = ii.attachmentUrl.replace(/\\/g, '/')
                                    }
                                }
                            }

                        }

                    }
                    this.tableData = arr;
                }
            });
        },
        // 导出 - 需选择是否要导出 追踪信息
        uploadOr() {
            this.uploadConfigFlag = true;
        },
        // 根据配置导出数据
        async uploadEdit() {
            this.uploadDataFlag = true;
            // try{
            this.$message.success("数据处理中, 请稍候!")
            let title = (this.userInfo.title || this.userInfo.nickname) + "的售前客户信息";
            let datas = [], data;
            if (this.userInfo.oriId) {
                data = await clientAndTrackExport({ oid: this.userInfo.oriId, customerType: 1 });
            } else {
                data = await clientAndTrackExport({ customerType: 1 });
            }
            if (data.code == 200) {
                if (data.data.length > 0) {
                    datas = data.data;
                } else {
                    this.$message.success("暂无数据导出");
                    this.uploadDataFlag = false;
                }
            } else {
                this.$message.success("获取失败");
                this.uploadDataFlag = false;
                return;
            }
            this.uploadConfigFlag = false;
            // 带有追踪信息的导出
            if (this.uploadConfig == 1) {
                // 将全部的 children 删除, 状态转换
                let statuns = {
                    // 客户状态
                    1: '成交客户',
                    2: '潜在客户',
                    3: '意向客户',
                    4: '失败客户'
                },
                    maturityns = {
                        1: 'A+明确成交意向',
                        2: 'A-有初步成交意向',
                        3: 'B+初步联系有意向',
                        4: 'B-初步联系意向是否成交',
                        5: 'C+明显拒绝',
                        6: 'C-无效客户'
                    };
                for (let v of datas) {
                    v.gender = v.gender == 1 ? '男' : '女';
                    v.customTag = v.customTag == 1 ? '是' : '否';
                    v.children = v.trackList;
                    delete v.trackList;
                    if (v.children.length > 0) {
                        v.children.forEach(item => {
                            item.status = statuns[item.status] || '未知';
                            item.maturity = maturityns[item.maturity] || '未知';
                            item.isDeal = item.isDeal == 1 ? '是' : '否';
                            item.attachmentUrl = item.attachmentUrl ? '是' : '否';
                        });
                    }
                }
                this.$message.success("打印中请稍候!");

                writeFun_array_tree(
                    datas,
                    { title: '平台名称', parentName: '家长姓名', studentName: '学生名称', phone: '手机号', subjectName: '科目名称', editionName: '版本名称', learningGradeName: '学习年级', gradeName: '年级名称', customTag: '是否自定义客户', createTime: '创建时间', remark: '备注' },
                    { status: '客户状态', maturity: '客户成熟度', isDeal: '是否成交', description: '文字描述', attachmentUrl: '是否有附件', createTime: '创建时间', updateTime: '修改时间' },
                    { title: title, rowspan: 2 },
                    '',
                    35,
                    { 1: 120, 3: 130, 5: 160, 6: 160 }
                );

                console.log("adasdass");

            } else {
                for (let v of datas) {
                    delete v['trackList'];
                    v.gender = v.gender == 1 ? '男' : '女';
                    v.customTag = v.customTag == 1 ? '是' : '否';
                }
                this.$message.success("打印中请稍候!");
                console.log('asdas');
                writeFun_array(
                    datas,
                    { title: title, rowspan: 2 },
                    { title: '平台名称', parentName: '家长姓名', studentName: '学生名称', phone: '手机号', subjectName: '科目名称', editionName: '版本名称', learningGradeName: '学习年级', gradeName: '年级名称', customTag: '是否自定义客户', createTime: '创建时间', remark: '备注' },
                    '',
                    '',
                    '',
                    '',
                    35,
                    { 9: 120, 10: 150 },
                    '',
                    false
                );
            }
            // }catch(err){
            //     console.log(err,"err");
            // }
            this.uploadDataFlag = false;
        },

        getAllBookList(param) {
            getAllBookList(param).then((res) => {
                let data = res.data;
                this.allBookData = res.data;
            });
        },

        getRelationBookList(param) {
            getRelationBookList(param).then((res) => {
                let data = res.data;
                this.relationBookList = res.data.map(Number);
            });
        },

        async getMechanismCampusList() {
            const res = await getMechanismCampusList({ channel: this.momaclassify.channel });
            let arr = [];
            if (res.data.length > 0) {
                for (let item of res.data) {
                    if (item.parentId) {
                        arr.push(item);
                    }
                }
            }
            this.orgArrs = arr;
        },

        // 平台查询
        async querySearch(queryString, cb) {
            // if (queryString == '') {
            //     this.listQuery.oid = '';
            //     return;
            // }
            const res = await getOrgList(queryString, this.momaclassify.channel);
            cb(res.data.data);
        },
        handleSelect(item) {
            this.listQuery.oid = item.id;
        },
        // 删除客户
        deleteAccount(data) {
            this.$confirm('将删除该自定义账号，是否继续', '提示', {
                onfirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                closeOnClickModal: false
            })
                .then(() => {
                    deleteClient({ id: data.id }).then((res) => {
                        if (res.code == 200) {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                            this.getClientList(this.listQuery);
                        } else {
                            this.$message({
                                type: 'error',
                                message: '操作失败!'
                            });
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消!'
                    });
                });
        },
        clearSelect() {
            this.$set(this.listQuery, 'campusId', '');
        },
        changeOid(id) {
            let self = this;
            if (self.listQuery.campusId) {
                self.$set(self.listQuery, 'campusId', '');
            }
        },

        // 触发搜索按钮
        handleSearchList() {
            this.$set(this.listQuery, 'pageNum', 1);
            this.getClientList({ ...this.listQuery, ...defaultListQuery });
        },
        handleResetSearch() {
            this.oidValue = '';
            this.listQuery = Object.assign({ oid: '' }, defaultListQuery, { oid: this.userInfo.oriId });
            this.handleSearchList();
        },
        closeDig() {
            this.editVisible = false;
        },

        // 获取授权的课程
        getGradeSubjectTime(oid) {
            // 获取授权的学科
            if (oid) {
                getGradeSubjectTime(oid).then(res => {
                    if (res.code == 200) {
                        let arr = res.data,
                            arrs = [];
                        for (let item of arr) {
                            for (let item1 of this.allBookData) {
                                if (item.id == item1.id) {
                                    arrs.push(item1);
                                    break;
                                }
                            }
                        }
                        this.subjectOK = arr;
                        this.allBookData = arrs || this.allBookData;
                    }
                }).catch();
            }
        },

        // 编辑操作
        handleEdit(row) {
            this.tit = '编辑客户';
            this.form = JSON.parse(JSON.stringify(row));

            this.editVisible = true;
        },
        // 添加客户
        addOr() {
            this.tit = '添加客户';
            this.form = { oid: this.userInfo.oriId };
            this.editVisible = true;
            this.resetForm('form');
            this.getGradeSubjectTime(this.form.oid);
        },
        // 添加追踪
        addTrack(row) {
            this.titTrack = '添加追踪';
            this.fileList = [];  // 清空文件
            this.trackform = { clientId: row.id };
            this.editVisibleTrack = true;
            this.resetForm('trackform');
        },
        // 修改追踪
        updateTrack(row) {
            this.titTrack = '编辑追踪';
            let id = row.clientId; // 客户Id
            for (let item of this.tableData) {
                if (item.id == id) {
                    row['clientName'] = item.parentName;
                    break;
                }
            }
            // 判断是否有文件
            this.fileList = [];
            if (row.attachmentUrl) {
                let name = row.attachmentUrl.split("/").slice(-1)[0];
                this.fileList = [{ name, urlReview: this.reviewURI + row.attachmentUrl, urlUpload: this.reviewURI + row.attachmentUrl }];
            }

            this.trackform = JSON.parse(JSON.stringify(row));
            this.editVisibleTrack = true;
        },
        // form的规则的重置
        resetForm(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].resetFields();
            }
        },

        // 新增 / 编辑 - 客户的
        saveEdit() {
            this.$refs.form.validate((valid) => {
                if (!valid) {
                    return false;
                }
                // 添加
                if (this.tit == '添加客户') {
                    this.form.gender = 1;
                    addClient(this.form)
                        .then((res) => {
                            if (res.code == 200) {
                                this.$notify({
                                    title: '操作成功',
                                    message: res.message,
                                    type: 'success'
                                });
                                this.editVisible = false;
                                // 需要加总页数的
                                // this.form.children = [];
                                // this.form.showExpand = false;
                                // this.tableData.unshift(this.form)
                                // if (this.tableData.length == 11) {
                                //     this.tableData.pop();
                                // }
                                // this.pageTotal++;
                                // this.listQuery.pageSize = Math.ceil(this.pageTotal / 10);
                                this.getClientList(this.listQuery);
                            } else {
                                this.$notify({
                                    title: '操作失败',
                                    message: res.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch((err) => { });
                }
                // 修改
                else {
                    updateClientInfo(this.form)
                        .then(async (res) => {
                            if (res.code == 200) {
                                // this.$notify({
                                //     title: '修改成功',
                                //     message: res.message,
                                //     type: 'success'
                                // });
                                this.$message.success(res.message)
                                this.editVisible = false;
                                for (let item of this.tableData) {
                                    if (item.id == this.form.id) {
                                        for (let v in this.form) {
                                            if (v == 'children') { continue; }
                                            item[v] = this.form[v];
                                        }
                                        break;
                                    }
                                }
                                this.$set(this.tableData);

                            } else {
                                this.$notify({
                                    title: '修改失败',
                                    message: res.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch((err) => { });
                }
            })

        },
        // 文件的保存 -- 顺序的，先上传/修改文件再上传/修改内容
        saveFileTrack() {
            // 判断是否有上传的文件名
            let uploadFlag = false;
            for (let item of this.fileList) {
                if (item.status == "ready") {
                    uploadFlag = true;
                    break;
                }
            }
            // 上传文件
            if (uploadFlag) {
                this.$on("upload", this.saveEditTrack);
                this.$refs.upload.submit();
            }
        },
        // 新增 / 编辑 - 追踪的 - 文件的上传
        // attachmentUrl -- 文件名
        saveEditTrack(attachmentUrl) {
            try {
                this.$off("upload", this.saveEditTrack);
            } catch (err) { return; }
            if (attachmentUrl) {
                this.trackform['attachmentUrl'] = attachmentUrl;
            } else if (this.fileList.length == 0) {
                this.trackform['attachmentUrl'] = "";
            }
            this.$refs.trackform.validate(async (valid) => {
                if (valid) {
                    let res;
                    let clientId = this.trackform['clientId'];
                    if (this.titTrack == '添加追踪') {
                        this.trackform.createTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                        res = await addOrUpdateTrack(this.trackform);
                        if (res.code == 200) {
                            this.$notify({
                                title: '操作成功',
                                type: 'success'
                            });
                            this.editVisibleTrack = false;
                            // 刷新局部数据
                            let arrchild = await selectTrackList({ clientId });
                            if (arrchild['code'] == 200) {
                                for (let item of this.tableData) {
                                    if (item.id == clientId) {
                                        item.children = arrchild['data'];
                                        item.showExpand = true;
                                        break;
                                    }
                                }
                                this.$set(this.tableData);

                            }
                        }
                    }
                    // 修改
                    else {
                        this.trackform.updateTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                        delete this.trackform['clientId'];
                        res = await addOrUpdateTrack(this.trackform);
                        if (res.code == 200) {
                            this.$message.success("修改成功")
                            this.editVisibleTrack = false;
                            // 判断是否有修改文件名
                            let arrs = JSON.parse(JSON.stringify(this.tableData))
                            for (let item of arrs) {
                                if (item.id == clientId) {
                                    for (let v of item.children) {
                                        if (v.id == this.trackform.id) {
                                            for (let v1 in this.trackform) {
                                                v[v1] = this.trackform[v1];
                                            }
                                            // 是否更改文件名

                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                            this.tableData = arrs;
                            await this.$nextTick();
                            if (clientId > 0) {
                                this.showhideRowExpand(clientId, true);
                            }
                        } else {
                            this.$notify({
                                title: '修改失败',
                                message: res.message,
                                type: 'error'
                            });
                        }
                    }


                }

            })

        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.listQuery, 'pageNum', val);
            this.getClientList({ ...this.listQuery, channel: this.momaclassify.channel });
        }
    }
};
</script>

<style lang="scss">
.hideExpandDiv {
    position: absolute;
    width: 40PX;
    height: 40px;
    font-size: 12px;
    color: white;
    font-weight: bold;
    background-color: rgb(243, 22, 22);
    right: 40px;
    bottom: 100px;
    text-align: center;
    line-height: 40px;
    z-index: 5;
    opacity: 0.5;
    cursor: pointer;
    border-radius: 50%;
}

.hideExpandDiv:hover {
    opacity: 1;
}

.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.or-add-btn {
    margin-bottom: 20px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}

.tableNest {
    // width: 97%;
    // margin-left: 3%;
    // background-color: #ff0000
}

.uploadClass .el-upload--text {
    display: inline;
    width: 100px;
    height: 60px;
    border: 0;
    box-shadow: none;
}

.mytable .row-expand-cover td .el-table__expand-icon {
    visibility: hidden;
}

.previewDiv {
    margin-top: 4vh !important;
}

.previewDivContent {
    position: relative;
    width: 96%;
    height: 96%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    margin: 0 auto;
}

.previewDivBack {
    font-size: 22PX;
    font-weight: bold;
    text-align: right;
    color: rgba(0, 0, 0, 0.7);
    height: 40Px;
    line-height: 40PX;
}

.previewDivBody {
    flex: 1;
}

.previewDivIframe {
    width: 100%;
    height: 80vh;
    border: 0;
    overflow: auto;
}

.mytable .el-table__expand-icon {
    background-color: #409eff;
    color: white;
    border-radius: 50%;
    width: 0.3rem;
    height: 0.3rem;
}
</style>
